import { UserState } from '@/stores/user'
import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'

// 创建 Axios 实例
const http: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: import.meta.env.VITE_API_TIMEOUT || 10000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器
http.interceptors.request.use((request) => {
  // 往请求头添加token
  const userState = UserState()

  if (userState.token != '') {
    request.headers.set('satoken', userState.token)
  }
  return request
})

// 响应拦截器
http.interceptors.response.use(
  (response) => {
    const { code, msg, data } = response.data
    if (code === 200) {
      return data
    } else {
      console.log(msg)
      return Promise.reject(new Error(msg))
    }
  },
  (error) => {
    ElMessage.error('请求失败，请检查网络状态')
    console.log(error.message)
  },
)

export const requests = {
  get: <T = unknown>(url: string, config?: AxiosRequestConfig): Promise<T> => http.get(url, config),

  post: <T = unknown>(url: string, data?: object, config?: AxiosRequestConfig): Promise<T> =>
    http.post(url, data, config),

  put: <T = unknown>(url: string, data?: object, config?: AxiosRequestConfig): Promise<T> =>
    http.put(url, data, config),

  delete: <T = unknown>(url: string, config?: AxiosRequestConfig): Promise<T> =>
    http.delete(url, config),
}
